import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'function.dart';
import 'model/device_model.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:async';

class DownloadPage extends StatefulWidget {
  DownloadPage(this.device, this.mainColor);
  final DeviceModel device;
  final mainColor;
  @override
  _DownloadPageState createState() => new _DownloadPageState(device);
}

class _DownloadPageState extends State<DownloadPage> with TickerProviderStateMixin {
  List unTasks = [];
  List cpTasks = [];
  int dlNum = 0;
  int cpNum = 0;
  DeviceModel device;
  String link = "";
  _DownloadPageState(this.device) {
    downloadLogin();
  }

  downloadLogin() async {
    var dlInfo = await remoteLogin(device.sessionid, device.userid, device.peerid);
    if (dlInfo['rtn'] == 0) {
      await uncompleteTask(true);
      await completeTask(true);
      if (mounted) {
        new Timer(new Duration(seconds: 2), downloadLogin);
      }
    } else {
      Map loginInfo = await doLogin(id: device.id, account: device.account, password: device.password, deviceid: device.device_id, imeiid: device.imeiid);
      if (loginInfo != null) {
        print("重新登录成功");
        device.sessionid = loginInfo['sessionid'];
        device.userid = loginInfo['userid'];
      }
      await downloadLogin();
    }
  }

  Future uncompleteTask(bool up) async {
    var taskData = await getDownloadTask(device.sessionid, device.userid, device.peerid, 5);

    if (taskData['rtn'] == 0) {
      this.dlNum = taskData['dlNum'];
      this.cpNum = taskData['completeNum'];
      this.unTasks = taskData['tasks'];
    }
    if (mounted) {
      setState(() {});
    }
  }

  Future completeTask(bool up) async {
    var taskData = await getDownloadTask(device.sessionid, device.userid, device.peerid, 1);
    if (taskData['rtn'] == 0) {
      this.cpTasks = taskData['tasks'];
    }
    if (mounted) {
      setState(() {});
    }
  }

  Widget _buildUnTasks(Map task) {
    return new Column(
      children: <Widget>[
        new ListTile(
          title: new Text(
            task['name'],
            style: new TextStyle(fontSize: 16.0),
          ),
          subtitle: new Row(
            children: <Widget>[
              new Text(
                task['failCode'] == 0 ? (task['state'] == 9 ? "已暂停" : convertSize(task['speed'], decimal: 2) + "/s") : "下载失败",
                style: new TextStyle(fontSize: 12.0),
              ),
              new SizedBox(
                width: 5.0,
              ),
              new Text(
                convertSize(task['progress'] * int.parse(task['size']) / 10000, decimal: 2) + "/" + convertSize(int.parse(task['size']), decimal: 2),
                style: new TextStyle(fontSize: 12.0),
              ),
              new SizedBox(
                width: 5.0,
              ),
              new Text(
                "剩余:${task['remainTime']} s",
                style: new TextStyle(fontSize: 12.0),
              ),
            ],
          ),
          trailing: new Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new CupertinoButton(
                child: task['state'] == 9
                    ? new Icon(
                        Icons.play_arrow,
                        color: Colors.green,
                      )
                    : new Icon(
                        Icons.pause,
                        color: Colors.red,
                      ),
                padding: EdgeInsets.all(0.0),
                onPressed: () async {
                  var res;
                  if (task['state'] == 9) {
                    print("开始");
                    List<String> tasks = ["${task['id']}_0"];
                    res = await downloadStart(device.sessionid, device.userid, device.peerid, tasks);
                    if (res['rtn'] == 0) {
                      toast("已继续下载");
                    } else {
                      toast("操作失败，请重试");
                    }
                  } else {
                    print("暂停");
                    List<String> tasks = ["${task['id']}_9"];
                    res = await downloadPause(device.sessionid, device.userid, device.peerid, tasks);
                    if (res['rtn'] == 0) {
                      toast("已暂停下载");
                    } else {
                      toast("操作失败，请重试");
                    }
                  }
                },
              ),
              new CupertinoButton(
                child: new Icon(
                  Icons.delete_forever,
                  color: Colors.red,
                ),
                onPressed: () {
                  showDialog<Null>(
                    context: context,
                    builder: (context) {
                      return new AlertDialog(
                        title: new Text("删除确认"),
                        content: new RepaintBoundary(
                          child: new Text("请选择要删除的内容"),
                        ),
                        actions: <Widget>[
                          new FlatButton(
                            child: new Text(
                              "任务和文件",
                            ),
                            padding: EdgeInsets.all(0.0),
                            onPressed: () async {
                              Navigator.of(context).pop();
                              print(task);
                              List<String> tasks = ["${task['id']}_${task['state']}"];
                              bool deleteFile = true;
                              var delResult = await downloadDelete(device.sessionid, device.userid, device.peerid, tasks, deleteFile);
                              if (delResult['rtn'] == 0) {
                                toast("删除任务和文件成功");
                              } else {
                                toast(delResult['msg']);
                              }
                            },
                          ),
                          new FlatButton(
                            child: new Text(
                              "仅任务",
                            ),
                            padding: EdgeInsets.all(0.0),
                            onPressed: () async {
                              Navigator.of(context).pop();
                              List<String> tasks = ["${task['id']}_${task['state']}"];
                              bool deleteFile = false;
                              var delResult = await downloadDelete(device.sessionid, device.userid, device.peerid, tasks, deleteFile);
                              if (delResult['rtn'] == 0) {
                                toast("删除任务成功");
                              } else {
                                toast(delResult['msg']);
                              }
                            },
                          ),
                          new FlatButton(
                            onPressed: () async {
                              Navigator.of(context).pop();
                            },
                            child: new Text(
                              '取消',
                            ),
                          ),
                        ],
                      );
                    },
                  );
                },
              ),
            ],
          ),
        ),
        Divider(height: 1.0),
      ],
    );
  }

  Widget _buildCpTasks(Map task) {
    return new Column(
      children: <Widget>[
        new ListTile(
          title: new Text(
            task['name'],
            style: new TextStyle(fontSize: 16.0),
          ),
          subtitle: new Row(
            children: <Widget>[
              new Text(
                convertTime(task['createTime']),
                style: new TextStyle(fontSize: 12.0),
              ),
              new SizedBox(
                width: 5.0,
              ),
              new Text(
                convertSize(task['progress'] * int.parse(task['size']) / 10000, decimal: 2),
                style: new TextStyle(fontSize: 12.0),
              ),
            ],
          ),
          trailing: new PopupMenuButton<String>(
            padding: const EdgeInsets.all(2.0),
            elevation: 2.0,
            onSelected: (String value) async {
              switch (value) {
                case "copy":
                  if (task['url'] == "") {
                    toast("下载地址不存在");
                  } else {
                    Clipboard.setData(new ClipboardData(text: task['url']));
                    toast("已复制");
                  }

                  break;
                case "source":
                  if (task['refer'] == "") {
                    toast("源网站不存在");
                  } else {
                    launch(task['refer']);
                  }

                  break;
                case "delete":
                  showDialog<Null>(
                    context: context,
                    builder: (context) {
                      return new AlertDialog(
                        title: new Text("删除确认"),
                        content: new RepaintBoundary(
                          child: new Text("请选择要删除的内容"),
                        ),
                        actions: <Widget>[
                          new FlatButton(
                            child: new Text(
                              "任务和文件",
                            ),
                            padding: EdgeInsets.all(0.0),
                            onPressed: () async {
                              Navigator.of(context).pop();
                              List<String> tasks = ["${task['id']}_${task['state']}"];
                              bool deleteFile = true;
                              var delResult = await downloadDelete(device.sessionid, device.userid, device.peerid, tasks, deleteFile);
                              if (delResult['rtn'] == 0) {
                                toast("删除任务和文件成功");
                              } else {
                                toast(delResult['msg']);
                              }
                            },
                          ),
                          new FlatButton(
                            child: new Text(
                              "仅任务",
                            ),
                            padding: EdgeInsets.all(0.0),
                            onPressed: () async {
                              Navigator.of(context).pop();
                              List<String> tasks = ["${task['id']}_${task['state']}"];
                              bool deleteFile = false;
                              var delResult = await downloadDelete(device.sessionid, device.userid, device.peerid, tasks, deleteFile);
                              if (delResult['rtn'] == 0) {
                                toast("删除任务成功");
                              } else {
                                toast(delResult['msg']);
                              }
                            },
                          ),
                          new FlatButton(
                            onPressed: () async {
                              Navigator.of(context).pop();
                            },
                            child: new Text(
                              '取消',
                            ),
                          ),
                        ],
                      );
                    },
                  );
                  break;
              }
            },
            itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
                  const PopupMenuItem<String>(
                    value: 'copy',
                    child: const ListTile(
                      leading: const Icon(Icons.person_add),
                      title: const Text('复制下载链接'),
                    ),
                  ),
                  const PopupMenuItem<String>(
                    value: 'source',
                    child: const ListTile(
                      leading: const Icon(Icons.import_export),
                      title: const Text('访问源网站'),
                    ),
                  ),
                  const PopupMenuItem<String>(
                    value: 'delete',
                    child: const ListTile(
                      leading: const Icon(Icons.delete_forever),
                      title: const Text('删除任务'),
                    ),
                  )
                ],
          ),
        ),
        Divider(height: 1.0),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return new DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: new CupertinoNavigationBar(
          actionsForegroundColor: Colors.white,
          backgroundColor: widget.mainColor,
          middle: new Text(
            "远程下载",
            style: new TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.normal,
            ),
          ),

          trailing: new CupertinoButton(
            minSize: 22.0,
            padding: EdgeInsets.all(0.0),
            child: new Icon(
              Icons.add,
              color: Colors.white,
              size: 20.0,
            ),
            onPressed: () {
              showDialog<Null>(
                context: context,
                builder: (context) {
                  return new AlertDialog(
                    title: new Text("创建任务"),
                    content: new RepaintBoundary(
                      child: new TextField(
                        decoration: new InputDecoration(
                          hintText: '请输入下载链接',
                          labelText: "下载链接",
                        ),
                        onChanged: (value) {
                          link = value;
                        },
                      ),
                    ),
                    actions: <Widget>[
                      new FlatButton(
                        child: new Text(
                          "下载",
                        ),
                        padding: EdgeInsets.all(0.0),
                        onPressed: () async {
                          var resolveRes = await urlResolve(device.sessionid, device.userid, device.peerid, link);
                          print(resolveRes['taskInfo']['name']);
                          print(resolveRes['taskInfo']['size']);
                          if (resolveRes['rtn'] == 0) {
                            Navigator.of(context).pop();
                            showDialog<Null>(
                              context: context,
                              builder: (context) {
                                return new AlertDialog(
                                  title: new Text("下载详情"),
                                  content: new Column(
                                    mainAxisSize: MainAxisSize.min,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      new Text(
                                        '文件名：${resolveRes['taskInfo']['name']}',
                                        textAlign: TextAlign.left,
                                      ),
                                      new Text(
                                        '大小：${convertSize(int.parse(resolveRes['taskInfo']['size']))}',
                                        textAlign: TextAlign.left,
                                      ),
                                      new Text(
                                        "请选择保存磁盘，磁盘1为近网口磁盘，磁盘2为非近网口磁盘",
                                        style: new TextStyle(color: Colors.red),
                                      ),
                                    ],
                                  ),
                                  actions: <Widget>[
                                    new FlatButton(
                                      child: new Text(
                                        "磁盘1",
                                      ),
                                      padding: EdgeInsets.all(0.0),
                                      onPressed: () async {
                                        var resolveRes = await urlResolve(device.sessionid, device.userid, device.peerid, link);
                                        print(resolveRes['taskInfo']['name']);
                                        print(resolveRes['taskInfo']['size']);
                                        if (resolveRes['rtn'] == 0) {
                                          var createRes = await createDlTask(
                                            device.sessionid,
                                            device.userid,
                                            device.peerid,
                                            link,
                                            resolveRes['taskInfo']['name'],
                                            resolveRes['taskInfo']['size'],
                                            true,
                                          );
                                          print(createRes);
                                          if (createRes['rtn'] == 0) {
                                            if (createRes['tasks'][0]['result'] == 0) {
                                              Navigator.of(context).pop();
                                              toast(resolveRes['taskInfo']['name'] + "开始下载");
                                            } else if (createRes['tasks'][0]['result'] == 202) {
                                              toast(resolveRes['taskInfo']['name'] + "已存在");
                                            } else {
                                              toast(createRes['tasks'][0]['msg']);
                                            }
                                          } else {
                                            toast("创建任务失败");
                                          }
                                        } else {
                                          toast("下载地址无效");
                                        }
                                      },
                                    ),
                                    new FlatButton(
                                      child: new Text(
                                        "磁盘2",
                                      ),
                                      padding: EdgeInsets.all(0.0),
                                      onPressed: () async {
                                        var resolveRes = await urlResolve(device.sessionid, device.userid, device.peerid, link);
                                        print(resolveRes['taskInfo']['name']);
                                        print(resolveRes['taskInfo']['size']);
                                        if (resolveRes['rtn'] == 0) {
                                          var createRes = await createDlTask(
                                            device.sessionid,
                                            device.userid,
                                            device.peerid,
                                            link,
                                            resolveRes['taskInfo']['name'],
                                            resolveRes['taskInfo']['size'],
                                            false,
                                          );
                                          print(createRes);
                                          if (createRes['rtn'] == 0) {
                                            if (createRes['tasks'][0]['result'] == 0) {
                                              toast(resolveRes['taskInfo']['name'] + "开始下载");
                                            } else if (createRes['tasks'][0]['result'] == 202) {
                                              toast(resolveRes['taskInfo']['name'] + "已存在");
                                            } else {
                                              toast(createRes['tasks'][0]['msg']);
                                            }
                                          } else {
                                            toast("创建任务失败");
                                          }
                                        } else {
                                          toast("下载地址无效");
                                        }
                                      },
                                    ),
                                    new FlatButton(
                                      onPressed: () async {
                                        Navigator.of(context).pop();
                                      },
                                      child: new Text(
                                        '取消',
                                      ),
                                    ),
                                  ],
                                );
                              },
                            );
                          } else {
                            toast("下载地址无效");
                          }
                        },
                      ),
                      new FlatButton(
                        onPressed: () async {
                          Navigator.of(context).pop();
                        },
                        child: new Text(
                          '取消',
                        ),
                      ),
                    ],
                  );
                },
              );
            },
          ),
        ),
        body: new Column(
          children: <Widget>[
            new TabBar(
              labelColor: widget.mainColor,
              indicatorColor: widget.mainColor,
              tabs: <Widget>[
                new Tab(
                  text: "未完成",
                ),
                new Tab(
                  text: "已完成",
                ),
              ],
            ),
            new Expanded(
              child: new TabBarView(
                children: <Widget>[
                  unTasks.length != 0
                      ? new ListView.builder(
                    itemBuilder: (context, i) => _buildUnTasks(unTasks[i]),
                    itemCount: unTasks.length,
                  )
                      : new Center(
                    child: new Text("无未完成下载"),
                  ),
                  cpTasks.length != 0
                      ? new ListView.builder(
                    itemBuilder: (context, i) => _buildCpTasks(cpTasks[i]),
                    itemCount: cpTasks.length,
                  )
                      : new Center(
                    child: new Text("无已完成下载"),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
